﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using System.Threading;
using OpenTK.Graphics;

namespace Clandestine.Graphics.Window
{
    public class GraphicsWindow
    {
        Thread thread;
        NativeWindow nw;
        bool created = false;
        bool pumpMustDie = false;
        object threadLock = new object();

        internal NativeWindow NativeWindow
        {
            get { return nw; }
        }

        public GraphicsWindow(int width, int height, string title, GameWindowFlags options, GraphicsMode mode, DisplayDevice device)
        {
            // Get all the parameters, package 'em up, and send them off to the new thread!
            thread = new Thread(new ParameterizedThreadStart(threadProc));
            object[] parameters = new object[] { width, height, title, options, mode, device };
            thread.Start((object)parameters);

            // Wait for window creation before returning control to the caller.
            while (!created)
                Thread.Sleep(20);
        }

        public void Stop()
        {
            pumpMustDie = true;
            lock (threadLock) { }
        }

        private void threadProc(object parameters)
        {
            // Unpack parameters, and create NativeWindow.
            object[] p = ((object[])parameters);
            nw = new NativeWindow((int)p[0], (int)p[1], (string)p[2], (GameWindowFlags)p[3], (GraphicsMode)p[4], (DisplayDevice)p[5]);
            created = true; // signal creation OK

            // Pump it!
            lock (threadLock)
            {
                while (!pumpMustDie)
                {
                    nw.ProcessEvents(); // pump message loop

                    #pragma warning disable 0612
                    nw.InputDriver.Poll(); // TODO: InputDriver is "obsolete", but OpenTK uses it in GameWindow and Input.Mouse, Input.Keyboard
                                           // haven't been written by them yet... Replace this when they have.
                    #pragma warning restore 0612

                    Thread.Sleep(20); // sleep. (.'. churn at ~50fps)
                }
            }
        }
    }
}
